<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md">
      <div class="text-center">
        <h2 class="mt-6 text-3xl font-extrabold text-gray-900">{{ APP_NAME }}</h2>
        <p class="mt-2 text-sm text-gray-600">{{ t("请输入您的账号密码登录系统") }}</p>
      </div>

      <el-form
          ref="loginForm"
          :model="form"
          :rules="rules"
          class="mt-8 space-y-6"
          @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
              v-model="form.username"
              :placeholder="t('请输入用户名')"
              prefix-icon="el-icon-user"/>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="form.password"
              type="password"
              :placeholder="t('请输入密码')"
              prefix-icon="el-icon-lock"
              show-password/>
        </el-form-item>

        <div class="flex items-center justify-between">
          <el-checkbox v-model="rememberMe">{{ t('记住我') }}</el-checkbox>
          <el-link underline="never" type="primary" @click="goToResetPassword">
            {{ t('忘记密码?') }}
          </el-link>
        </div>

        <div>
          <el-button
              type="primary"
              native-type="submit"
              class="w-full"
              :loading="loading">
            {{ t('登录') }}
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {useAuthStore} from '@/stores/auth'
import {APP_NAME} from "@/api/_const.js";
import {resetPassword} from "@/router/index.js";
import {useI18n} from "vue-i18n";

const {t} = useI18n()

const router = useRouter()
const authStore = useAuthStore()

const loginForm = ref(null)
const loading = ref(false)
const rememberMe = ref(false)

const form = ref({
  username: 'admin',
  password: 'admin'
})

const rules = ref({
  username: [{ required: true, message: t('请输入用户名'), trigger: 'blur' }],
  password: [{ required: true, message: t('请输入密码'), trigger: 'blur' }]
})

const handleLogin = async () => {
  try {
    loading.value = true
    await loginForm.value.validate()
    loading.value = true
    let res = await authStore.fetchLogin(form.value)
    if (res.code !== 200) {
      ElMessage.error(res.message)
      return
    }
    ElMessage.success(t('操作成功'))
    // 跳转到首页
    await router.push({path: '/'})
  } finally {
    loading.value = false
  }
}

const goToResetPassword = () => {
  router.push({ name: resetPassword })
}
</script>